package com.dmc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Assert;
import com.dmc.conf.Constant;
import com.dmc.dict.DistriButionPayTypeDict;
import com.dmc.dict.IntegralTranTypeDict;
import com.dmc.entity.Orders;
import com.dmc.mapper.*;
import com.dmc.model.*;
import com.dmc.service.CashOutOrderService;
import com.dmc.service.OrderReceiptService;
import com.dmc.service.UserAccountService;
import com.dmc.util.DecimalUtil;
import com.dmc.util.EmailUtils;
import com.dmc.util.util.OrderCodeUtil;
import com.dmc.util.util.SessionUtil;
import com.dmc.vo.CashOutOrdersVo;
import com.dmc.vo.DataTable;
import com.dmc.vo.OrderReceiptVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 发票 服务实现类
 * </p>
 *
 * @
 * @since 2020-09-05
 */
@Service
@Transactional
@Slf4j
public class OrderReceiptServiceImpl implements OrderReceiptService {


    @Autowired
    private OrderReceiptMapper orderReceiptMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DistributionOrderMapper distributionOrderMapper;

    @Autowired
    private DistributionOrderGoodsMapper distributionOrderGoodsMapper;

    @Override
    public OrderReceiptVo addOrderReceipt(OrderReceiptVo vo) {
        Long orderId = vo.getOrderId();
        Assert.notNull(orderId,"参数错误,请传输订单ID");
        Integer orderType = vo.getOrderType();
        Assert.notNull(orderType,"参数错误,请传输订单类型");
        //判断当前订单是否已经开具过发票
        OrderReceipt orderReceipt=new OrderReceipt();
        orderReceipt.setOrderId(orderId);
        orderReceipt=orderReceiptMapper.selectOne(orderReceipt);
        Assert.isNull(orderReceipt,"参数错误,此订单已经开具过发票");
        BigDecimal finalAmount = null;
        if(0 == orderType){
            Orders orders = ordersMapper.selectById(orderId);
            Assert.notNull(orders,"参数错误,无此订单");
            finalAmount = orders.getFinalAmount();
            Assert.isTrue(finalAmount!=null && finalAmount.compareTo(BigDecimal.ZERO)>0,"无法开具发票,此订单未使用金额支付");
        }else if(1 == orderType){
            DistributionOrder distributionOrder = distributionOrderMapper.selectById(orderId);
            Assert.notNull(distributionOrder,"参数错误,无此订单");
            Integer payType = distributionOrder.getPayType();
            Assert.isTrue(DistriButionPayTypeDict.checkCashPayType(payType),"无法开具发票,此订单未使用金额支付");
            DistributionOrderGoods distributionOrderGoods=new DistributionOrderGoods();
            distributionOrderGoods.setOrderId(orderId);
            distributionOrderGoods=distributionOrderGoodsMapper.selectOne(distributionOrderGoods);
            finalAmount = distributionOrderGoods.getPrice();
        }
        Long currUid = SessionUtil.getCurrUid();
        vo.setUserId(currUid);
        vo.setReceiptPrice(finalAmount);
        String receiptUserName = vo.getReceiptUserName();
        if(StringUtils.isBlank(receiptUserName)){
            User byId = userMapper.getById(currUid);
            vo.setReceiptUserName(byId.getUsername());
        }
        vo.setCreateTime(new Date());
        vo.setReceiptStatus(0);
        orderReceipt = new OrderReceipt();
        BeanUtil.copyProperties(vo,orderReceipt);
        orderReceiptMapper.insert(orderReceipt);
        return vo;
    }

    @Override
    public void updateOrderReceipt(OrderReceiptVo vo) {
        Long id = vo.getId();
        Assert.notNull(id,"参数错误,请传输ID");
        OrderReceipt orderReceipt = orderReceiptMapper.selectById(id);
        Assert.notNull(orderReceipt,"参数错误,无当发票数据");
        Integer status = orderReceipt.getReceiptStatus();
        Assert.isTrue(status<1,"已开具发票,无法进行修改");
        if(vo.getReceiptStatus() == 1) {
            vo.setReceiptTime(new Date());
        }
        BeanUtil.copyProperties(vo,orderReceipt,CopyOptions.create().setIgnoreNullValue(true));
        orderReceiptMapper.updateById(orderReceipt);
        if(vo.getReceiptStatus() == 1){
            //发送邮件
            String receiptUrl = orderReceipt.getReceiptUrl();
            Assert.isTrue(StringUtils.isNotBlank(receiptUrl),"无法发送邮件,发票地址为空");
            String email = orderReceipt.getEmail();
            Assert.isTrue(StringUtils.isNotBlank(email),"无法发送邮件,邮箱地址为空");
            boolean sendResult = EmailUtils.sendMail(email, "您的发票地址为:" + receiptUrl, "晶品城已为您开具发票,请注意查收");
            log.info("updateOrderReceipt ---结束1");
            Assert.isTrue(sendResult,"发送发票失败");
        }
        log.info("updateOrderReceipt ---结束2");
    }

    @Override
    public DataTable<OrderReceiptVo> getOrderReceiptList(OrderReceiptVo vo) {
        Integer start = vo.getStart();
        if(start == null){
            vo.setStart(0);
        }
        Integer length = vo.getLength();
        if(length == null){
            vo.setLength(10);
        }
        String userName = vo.getReceiptUserName();
        if(StringUtils.isNotBlank(userName)){
            vo.setReceiptUserName("%"+userName.trim()+"%");
        }
        String userPhone = vo.getPhone();
        if(StringUtils.isNotBlank(userPhone)){
            vo.setPhone("%"+userPhone.trim()+"%");
        }
        PageHelper.startPage(vo.getStart(), vo.getLength());
        List<OrderReceiptVo> list =  orderReceiptMapper.getOrderReceiptList(vo);
        DataTable<OrderReceiptVo> tables = new DataTable<>();
        tables.setRecordsTotal(((Page) list).getTotal());
        tables.setRecordsFiltered(tables.getRecordsTotal());
        tables.setDraw(vo.getDraw());
        tables.setData(list);
        return tables;
    }

    @Override
    public OrderReceiptVo getOrderReceiptByOrderId(OrderReceiptVo vo) {
        OrderReceiptVo result = null;
        List<OrderReceiptVo> list =  orderReceiptMapper.getOrderReceiptList(vo);
        if(list!=null && list.size()>0){
            result = list.get(0);
        }
        return result;
    }
}
